package com.corewillsoft.fireflies.gamelaws;

import android.util.FloatMath;

import com.corewillsoft.fireflies.gameobjects.AreaObject;
import com.corewillsoft.fireflies.gameobjects.Firefly;
import com.corewillsoft.fireflies.gameobjects.GameObject;

public class FrogFireflyLaw extends BaseLaw {
	private static final float INFLUENCE_RADIUS = 140f;  //distance where frog pulls firefly within
	private static final float KILLING_RADIUS = 30;		 //distance where frog kills firefly within
	private static final float FROG_FORCE = 2f;

	@Override
	public void applicate(GameObject gameObject) {
		if (gameObject instanceof Firefly)
			processFirefly((Firefly) gameObject);
	}

	private void processFirefly(Firefly firefly) {
		float fireflyCenterX = firefly.getX() + firefly.getWidth() / 2;
		float fireflyCenterY = firefly.getY() + firefly.getHeight() / 2;

		float frogCenterX = parent.getX() + parent.getWidth() / 2;
		float frogCenterY = parent.getY() + parent.getHeight() / 2;

		float dX = frogCenterX - fireflyCenterX;
		float dY = frogCenterY - fireflyCenterY;
		float length = FloatMath.sqrt(dX * dX + dY * dY);

		if (INFLUENCE_RADIUS < length)
			return;

		if ((length < INFLUENCE_RADIUS) && (length > KILLING_RADIUS)) {
			//frog pulls firefly towards itself

			//values of firefly speed increment along x an y axis
			float speedIncX = 0;
			float speedIncY = 0;

			if (0 < length) {
				speedIncX = FROG_FORCE * dX / length;
				speedIncY = FROG_FORCE * dY / length;
			}

			firefly.setSpeed(firefly.getSpeedX() + speedIncX, firefly.getSpeedY() + speedIncY);
		} else if (length < KILLING_RADIUS) {
			//frog kills firefly, and hides it (firefly is "eaten" and becomes invisible)
			firefly.setVisible(false);
			firefly.setAlive(false);
		}
	}

	/**
	 * Initializes influence area for frog-firefly law;
	 * frog can influence on firefly in the circle area with the center in the center of
	 * frog and with radius INFLUENCE_RADIUS;
	 * however, as far as influence area can be only rectangular (for now!),
	 * it is initialized by square with center in the center of frog and with sides equal 2 * INFLUENCE_RADIUS
	 */
	@Override
	public void initializeInfluenceArea() {
		if (parent == null) {
			setArea(null);
		} else {
			float parentCenterX = parent.getX() + parent.getWidth() / 2;
			float parentCenterY = parent.getY() + parent.getHeight() / 2;

			AreaObject influenceArea = new AreaObject(parentCenterX - INFLUENCE_RADIUS,
					parentCenterX + INFLUENCE_RADIUS,
					parentCenterY - INFLUENCE_RADIUS,
					parentCenterY + INFLUENCE_RADIUS);
			setArea(influenceArea);
		}
	}

	@Override
	public LawType getType() {
		return LawType.FROG_FIREFLY;
	}
}
